package com.unicom.projt.http;

import android.content.res.AssetManager;
import android.util.Log;
import com.unicom.projt.Const;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;


/**
 * HTTP连接工具。应 与GUI运行在不同线程下。
 */
public class HttpConnection {

    private boolean mAbort;// 是否主动关闭连接
    private HttpClient mClient;
    private HttpPost mPost;
    private String keyStorePath="";
    public static AssetManager assetManager;

    {
        keyStorePath=HttpConnection.class.getResource("/assets/server.keystore").toString();
    }

    public void abort() {
        mAbort = true;
        Log.e(Const.TAG, "HttpConnection:abort request");
        if (mPost != null) {
            mPost.abort();
        }
        closeConnection();
    }

    /**
     * 主动关闭网络连接。
     */
    public void closeConnection() {
        if (mClient != null) {
            Log.i(Const.TAG, "HttpConnection:close connection");
            mClient.getConnectionManager().shutdown();
        }
    }

    /**
     * 发起POST请求，取得响应字符串。如果HTTP StatusCode不是200，则返回null。
     *
     * @param uri
     * @return
     * @throws NetworkingException
     * @throws NetworkingAbortException
     */
    String post(UriConstants uri, String data)
            throws NetworkingException, NetworkingAbortException {
        Log.d(Const.TAG, "HttpConnection:HTTP POST excuting");
        mAbort = false;
        mClient = new DefaultHttpClient();

        KeyStore keyStore= null;
//        try {

//            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//            Log.e("KEY",assetManager.open ("server.keystore").toString());
//            keyStore.load(assetManager.open ("server.keystore"), "changeit".toCharArray());


//            SSLSocketFactory socketFactory=new SSLSocketFactory(keyStore);
//            Scheme scheme=new Scheme("https",socketFactory, 443);
//            mClient.getConnectionManager().getSchemeRegistry().register(scheme);
//        } catch (KeyStoreException e) {
//            e.printStackTrace();
//        } catch (CertificateException e) {
//            e.printStackTrace();
//        } catch (UnrecoverableKeyException e) {
//            e.printStackTrace();
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (KeyManagementException e) {
//            e.printStackTrace();
//        }

        BufferedReader br = null;
        String resp = null;
        try {
            mPost = new HttpPost(uri.getUri());
//			List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//			if (params != null) {
//				for (Entry<String, String> item : params.entrySet()) {
//					postParameters.add(new BasicNameValuePair(item.getKey(),
//							item.getValue()));
//				}
//			}
//			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
//					postParameters);
            StringEntity myEntity = new StringEntity(data, "utf-8");
            mPost.setEntity(myEntity);

            HttpConnectionParams.setConnectionTimeout(mPost.getParams(), 20 * 1000);

            HttpResponse response = mClient.execute(mPost);

//			br = new BufferedReader(new InputStreamReader(response.getEntity()
//					.getContent()));
//			String line = "";
            String newLine = System.getProperty("line.separator");
            StringBuffer sb = new StringBuffer("");
//			while ((line = br.readLine()) != null) {
//				sb.append(line + newLine);
//			}
            List<String> lines = IOUtils.readLines(response.getEntity().getContent(), "gb2312");
            for (String line : lines) {
                sb.append(line + newLine);
            }
            resp = sb.toString();
            Log.v(Const.TAG, "HttpConnection:response string:"
                    + resp);

            int statusCode = response.getStatusLine().getStatusCode();
            Log.d(Const.TAG,
                    "HttpConnection:response status code:" + statusCode);

            if (statusCode != HttpStatus.SC_OK) {
                Log.e(Const.TAG,
                        "HttpConnection:wrong response status code:"
                                + statusCode);
                Log.d(Const.TAG,
                        "HttpConnection:HTTP POST response string:"
                                + sb.toString());
                resp = null;
            }

        } catch (IOException e) {
            Log.e(Const.TAG, "HttpConnection:is aborted?"
                    + mAbort);
            Log.e(Const.TAG,
                    "HttpConnection:I/O exception:" + e.getStackTrace().toString());
            resp = null;
            if (!mAbort) {
                throw new NetworkingAbortException();
            } else {
                throw new NetworkingException(e);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                if (mClient != null) {
                    mClient.getConnectionManager().shutdown();
                    Log.i(Const.TAG,
                            "HttpConnection:connection closed");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d(Const.TAG, "HttpConnection:HTTP POST finished");
        return resp;
    }

}
